<script lang="ts" setup>
import { cancelOrder } from '@/api/car';
import { cancelUnpaidOrder } from '@/api/orders';
import { getPaymentResult, selectPayment } from '@/api/payment';
import { cancelOrder as cancelRestaurantBookingOrder } from '@/api/restaurant-booking';
import { useLocale } from '@/locale/locale';
import { RouteMap, useRouter } from '@/router';
import { isWechat } from '@/utils/platform';
import { onLoad } from '@dcloudio/uni-app';
import { reactive } from 'vue';

const { t } = useLocale();
const router = useRouter();

const data = reactive({
  orderSn: '',
  amount: 0,
  createTime: '',
  countdown: 0,
  payMethod: 'wechat',
  from: 'checkout',
  isFromOrder: false,
  orderIndex: -1,
  model: null
});

onLoad((options) => {
  data.orderSn = options!.id;
  data.amount = options!.amount;
  data.createTime = options!.createTime;
  data.countdown = options!.countdown;
  data.from = options!.from;
  data.isFromOrder = options!.isFromOrder ? options!.isFromOrder : false;
  data.orderIndex = options!.orderIndex ? options!.orderIndex : -1;
  data.model = options!.model;
});

async function checkPaymentResult() {
  const res = await getPaymentResult(data.orderSn);
  let path = RouteMap.orderDetails;
  let payload: any = { orderSn: data.orderSn };
  if (data.from === 'dining') {
    path = RouteMap.restaurantBookingDetails;
  } else if (data.from === 'car') {
    path = RouteMap.carOrderDetail;
  } else if (data.from === 'stayOn') {
    path = RouteMap.tripStayOnResult;
    payload = {
      tripId: data.orderSn,
      status: res.data.status === 'SUCCESS' ? 1 : 0,
      model: JSON.stringify(data.model)
    };
  } else if (data.from === 'trip_change') {
    return router.back();
  }
  if (data.isFromOrder && data.orderIndex < 0) {
    return router.back();
  }
  if (res.data.status === 'SUCCESS') {
    await router.to(path, payload, true);
  } else if (res.data.status === 'HC_DATE_FAIL、续住失败】') {
    await uni.showToast({ title: t('tripChangeStayOnFail'), icon: 'none' });
    await router.to(RouteMap.orders, { tab: data.from }, true);
  } else {
    await router.to(RouteMap.orders, { tab: data.from }, true);
  }
}

async function handlePay() {
  const r1 = await selectPayment({
    OrderSn: data.orderSn,
    payChannel: 'WeChatMiniPay'
  });
  if (r1.code === 0) {
    const params: Record<string, string> = JSON.parse(r1.data.wxMiniPayParams);
    try {
      await uni.requestPayment({
        provider: 'wxpay',
        orderInfo: {},
        timeStamp: params.timeStamp,
        nonceStr: params.nonceStr,
        package: params.package,
        signType: params.signType,
        paySign: params.paySign
      });
      await checkPaymentResult();
    } catch (error) {
      await uni.showLoading();
      if (!data.isFromOrder) {
        return router.to(RouteMap.orders, { tab: data.from }, true);
      } else {
        router.back();
      }
    }
  }
}

function handleCancel() {
  uni.showModal({
    content: t('LRKey_CancelPayment'),
    confirmText: t('LRKey_Yes'),
    cancelText: t('LRKey_no'),
    success: async (res) => {
      if (res.cancel) return void 0;
      if (data.from === 'dining') {
        await cancelRestaurantBookingOrder(data.orderSn);
      } else if (data.from === 'car') {
        await cancelOrder(data.orderSn, true);
      } else {
        await cancelUnpaidOrder(data.orderSn);
      }
      if (!data.isFromOrder) {
        return router.to(RouteMap.orders, { tab: data.from }, true);
      }
      if (data.orderIndex > -1) {
        let pages = getCurrentPages();
        let currentPage = pages[pages.length - 2];
        currentPage.$vm.changeOrderStatus('CANCEL', data.orderIndex);
      }
      router.back();
    }
  });
}
</script>

<template>
  <view class="payment-top-bg"></view>
  <view class="absolute top-0 left-0">
    <uni-nav-bar
      v-if="isWechat()"
      :border="false"
      background-color="transparent"
      color="#fff"
      fixed
      left-icon="left"
      status-bar
      @click-left="router.back"
    >
      <view class="payment-nav-title">{{ t('LRKey_pay') }}</view>
    </uni-nav-bar>

    <view class="flex flex-col justify-center items-center w-screen pt-1 mb-5">
      <text class="text-base text-white mb-1">{{ t('LOKey_orderAmountPay') }}</text>
      <view class="flex justify-center items-baseline text-white payment-actual-amount mb-2">
        <text>￥</text>
        <text class="payment-actual-amount-value">{{ data.amount }}</text>
        <text>JPY</text>
      </view>
      <apt-count-down v-if="data.countdown > 0" :countdown="data.countdown"></apt-count-down>
      <text class="text-base text-white">{{ t('LRKey_minsAfterCancel') }}</text>
    </view>

    <view class="payment-methods">
      <view class="payment-methods-line"></view>
      <view class="payment-methods-content">
        <view class="payment-methods-content__shadow-inset"></view>
        <view class="text-base text-primary mb-1">{{ t('LRKey_paymentMethod') }}</view>
        <view class="payment-methods-content__item">
          <image class="w-5 h-5" src="/static/icon_wechat.png" />
          <text class="flex-1 mx-3 text-lg text-primary font-medium">
            {{ t('LRKey_wxpay') }}
          </text>
          <image
            :src="
              data.payMethod !== 'wechat'
                ? '/static/icon_unchecked_gray.png'
                : '/static/icon_coupon_checked.png'
            "
            class="w-5 h-5"
          />
        </view>
        <view class="payment-methods-content__divider"></view>
        <view class="flex justify-between items-center py-1">
          <text class="text-base text-fourth">{{ t('LRKey_orderNo') }}</text>
          <text class="text-base text-fourth">{{ data.orderSn }}</text>
        </view>
        <view class="flex justify-between items-center py-1">
          <text class="text-base text-fourth">{{ t('LRKey_orderTime') }}</text>
          <text class="text-base text-fourth">{{ data.createTime }}</text>
        </view>
      </view>
    </view>

    <view class="payment-footer">
      <uv-button
        :custom-style="{ width: '330rpx', height: '76rpx' }"
        :text="t('LRKey_cancelPayment')"
        shape="circle"
        @click="handleCancel"
      />
      <uv-button
        :custom-style="{ width: '330rpx', height: '76rpx', backgroundColor: '#269c74' }"
        :text="t('LRKey_payNow')"
        shape="circle"
        type="primary"
        @click="handlePay"
      />
    </view>
  </view>
</template>

<style lang="scss">
.payment-top-bg {
  width: 100vw;
  height: 560rpx;
  background-color: #269c74;
}

.payment-methods {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 0 19rpx;

  &-line {
    width: 712rpx;
    height: 20rpx;
    background: #117954;
    border-radius: 112rpx 112rpx 112rpx 112rpx;
  }

  &-content {
    position: relative;
    top: -10rpx;
    width: 682rpx;
    padding: 40rpx 32rpx;
    background: #ffffff;
    box-shadow: 0 16rpx 48rpx 0 rgba(149, 157, 165, 0.2);

    &__shadow-inset {
      position: absolute;
      top: 0;
      left: 0;
      width: 682rpx;
      height: 20rpx;
      background: linear-gradient(180deg, rgba(18, 121, 85, 0.42) 0%, rgba(19, 122, 85, 0) 100%);
    }

    &__item {
      display: flex;
      align-items: center;
      padding: 38rpx 0;
    }

    &__divider {
      margin-top: 40rpx;
      margin-bottom: 20rpx;
      height: 4rpx;
      background-color: #f4f4f4;
    }
  }
}

.payment-nav-title {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  font-size: 36rpx;
  font-weight: 500;
  color: #fff;
}

.payment-actual-amount {
  font-size: 32rpx;
  line-height: 64rpx;

  &-value {
    font-size: 64rpx;
  }
}

.payment-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 60rpx;
  padding: 0 34rpx;
}
</style>
